<?php

namespace app\admin\controller\service;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\service\Order;
use app\common\model\service\order\Info;
use app\common\model\User as ModelUser;
use app\common\model\UserGroup;
use think\Db;
use think\Exception;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index($ids = "")
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignConfig('ids', $ids);
        return $this->view->fetch();
    }


    /**
     * 派单
     */
    public function dispatch($ids = "")
    {

        $get = $this->request->get();
        extract($get);
        $order = Order::with(['info'])->find($order_id, ['info']);
        if (!$order) {
            $this->error(__('订单不存在'));
        }
        if ($order->status == '5') {
            $this->error(__('已派单'));
        }
        Db::startTrans();
        try {
            $escort = ModelUser::get($ids);
            $user = ModelUser::get($order->user_id);
            $group = UserGroup::column('id,proportion');
            if (!$escort->group_id) {
                $this->error('该陪诊师未分配组别');
            }
            $proportion = $group[$escort->group_id];
            $commission = bcmul($order->total_amount, bcdiv($proportion, 100, 2), 2);

            $phone = Order::bing_telephone($escort->mobile, $user->mobile, $order_id);


            $order->save(['escort_id' => $ids, 'status' => '5', 'commission' => $commission, 'virtual_telephone' => $phone]);
            Info::where('id', $order['info'][0]['id'])->update(['commission' => $commission]);
           
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('派单失败：' . $e->getMessage());
        }
        $this->success();
    }
  
}
